package com.huohuo.javabasic;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {

    private String path;//加载类的路径
    private String name;//类加载器名称

    public MyClassLoader(String name, String path) {
        this.name = name;
        this.path = path;
    }

    public MyClassLoader(ClassLoader parent, String name, String path) {
        super( parent );//让系统的类加载器成为该类的父加载器
        this.name = name;
        this.path = path;
    }

    /*@Override
    public String toString() {
        return super.toString();
    }*/

    @Override
    public String toString() {
        return this.name;
    }

    /**
     * 通过我们自己定义的类加载器，加载某个类
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    protected Class<?> findClass(String name) throws ClassNotFoundException {
         byte [] data = readClassFileToByteArray(name);
         ///返回当前自定义加载器
        if (data ==null){
            return null;
        }
         return this.defineClass( name,data,0,data.length );
    }


    private byte[] readClassFileToByteArray(String name) {
        InputStream is = null;
        byte[] returnData = null;
        name = name.replaceAll( "\\.", "/" );
        String filePath = this.path + name + ".class";
        File file = new File( filePath );
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            is = new FileInputStream( file );
            int tmp = 0;
            while ((tmp = is.read()) != -1) {
                os.write( tmp );
            }
            returnData = os.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                os.close();
            } catch (Exception e2) {
            }
        }
        return returnData;
    }

}